package com.schoolcloud.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.schoolcloud.common.exception.UserNotExistException;
import com.schoolcloud.common.model.PageDTO;
import com.schoolcloud.system.query.SysUseQuery;
import com.schoolcloud.system.service.SysPermissionService;
import com.schoolcloud.system.service.SysUserService;
import com.schoolcloud.system.entity.SysUser;
import com.schoolcloud.system.mapper.SysUserMapper;
import com.schoolcloud.system.vo.SysUserInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
@RequiredArgsConstructor
public class SysUserServiceImpl implements SysUserService {

    private final SysUserMapper sysUserMapper;
    private final SysPermissionService permissionService;

    @Override
    public String selectUserByUserNameAndPassword(String userName, String password) throws UserNotExistException {
        SysUser user = new SysUser();
        user.setUserName(userName);
        user = sysUserMapper.selectUser(user);
        String queryPassword = user.getPassword();
//            获取盐值，并拼接密码，然后比较
        String salt = user.getSalt();
        String md5 = SecureUtil.md5(password + salt);
        if (queryPassword.equals(md5)) {
//            登录成功返回用户id
            return user.getUserId().toString();
        }
//        密码输入错误或者用户不存在
        throw new UserNotExistException();
    }

    @Override
    public void addUser(SysUser sysUser) {
//        加密密码存储
        String s = RandomUtil.randomString(5);//生成随机值作为md5的盐值
        sysUser.setSalt(s);
        String md5Password = SecureUtil.md5(sysUser.getPassword() + s);
        sysUser.setPassword(md5Password);
        sysUserMapper.addUser(sysUser);
    }

    @Override
    public SysUserInfoVO getSysUserInfo(String userId) {
        SysUserInfoVO userInfoVO = permissionService.getUserPermissions(userId);
        SysUser user= sysUserMapper.selectUserInfoById(userId);
        userInfoVO.setSysUser(user);
        return userInfoVO;
    }

    @Override
    public List<SysUser> getSysUserList(SysUseQuery sysUseSearchDTO) {
        return sysUserMapper.getSysUserList(sysUseSearchDTO);
    }

    @Override
    public void modifySysUser(SysUser sysUser) {
        sysUserMapper.modifySysUser(sysUser);
    }

    @Override
    public PageDTO<SysUser> getSysUserPage(SysUseQuery sysUseSearchDTO) {
        PageDTO<SysUser> dto = new PageDTO<>();
        List<SysUser> sysUserList = getSysUserList(sysUseSearchDTO);
        dto.setList(sysUserList);
        dto.setTotal(sysUserMapper.getSysUserCount(sysUseSearchDTO));
        dto.setPageNum(sysUseSearchDTO.getPageNum());
        return dto;
    }
}
